package com.example.community.Interceptor;

import com.example.community.dto.UserDto;
import com.example.community.enums.AdPosEnum;
import com.example.community.exception.CustomizeErrorCode;
import com.example.community.exception.CustomizeException;
import com.example.community.mapper.AdminMapper;
import com.example.community.mapper.GiteeUserMapper;
import com.example.community.mapper.UserMapper;
import com.example.community.model.*;
import com.example.community.service.AdService;
import com.example.community.service.NotificationService;
import com.example.community.util.CookieChecking;
import com.example.community.util.GetIpAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class SessionInterceptor implements HandlerInterceptor {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private GiteeUserMapper giteeUserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private NotificationService notificationService;
    @Autowired
    private AdService adService;


    @Value("${gitee.oauth.redirect_url}")
    private String giteeRedirectUri;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //设置 context 级别的属性
        request.getServletContext().setAttribute("giteeRedirectUri", giteeRedirectUri);
        // 没有登录的时候也可以查看导航
        for (AdPosEnum adPos : AdPosEnum.values()) {
            request.getServletContext().setAttribute(adPos.name(), adService.list(adPos.name()));
        }
        Cookie[] cookies = request.getCookies();
        String token = CookieChecking.CookieToken(cookies,"token");
        if (token != null){
            String type = token.substring(0,2);
            String userToken = token.substring(2);

            if (type.equals("GU")) {
                GiteeUserExample giteeUserExample = new GiteeUserExample();
                giteeUserExample.createCriteria()
                        .andTokenEqualTo(userToken);
                List<GiteeUser> giteeUsers = giteeUserMapper.selectByExample(giteeUserExample);
                if (giteeUsers.size() != 0) {
                    GiteeUser giteeUser = giteeUsers.get(0);
                    if (System.currentTimeMillis() - giteeUser.getGmtModified() > 1000 * 60 * 60){
                        GiteeUserExample updateGiteeUserIp = new GiteeUserExample();
                        giteeUserExample.createCriteria().andIdEqualTo(giteeUser.getId());
                        GiteeUser updateGiteeUser = new GiteeUser();
                        updateGiteeUser.setIp(GetIpAddress.getIp(request));
                        giteeUser.setIp(updateGiteeUser.getIp());
                        updateGiteeUser.setGmtModified(System.currentTimeMillis());
                        giteeUserMapper.updateByExampleSelective(updateGiteeUser,updateGiteeUserIp);
                    }
                    HttpSession session = request.getSession();
                    UserDto userDto = UserDto.getUserDtoByGiteeUser(giteeUser);
                    session.setAttribute("user", userDto);
                    Long unreadCount = notificationService.unreadCount(giteeUser.getId(),1);
                    session.setAttribute("unreadCount", unreadCount);
                }
            }
            else if (type.equals("UR")){
                UserExample userExample = new UserExample();
                userExample.createCriteria()
                        .andTokenEqualTo(userToken);
                List<User> users = userMapper.selectByExample(userExample);
                if (users.size() > 0){
                    User user = users.get(0);
                    //System.currentTimeMillis() - user.getGmtModified() > 1000 * 60 * 60
                    if (System.currentTimeMillis() - user.getGmtModified() > 1000 * 60 * 60){
                        UserExample updateUserIp = new UserExample();
                        updateUserIp.createCriteria().andIdEqualTo(user.getId());
                        User updateUser = new User();
                        updateUser.setGmtModified(System.currentTimeMillis());
                        updateUser.setIp(GetIpAddress.getIp(request));
                        user.setIp(updateUser.getIp());
                        userMapper.updateByExampleSelective(updateUser,updateUserIp);
                    }
                    HttpSession session = request.getSession();
                    UserDto userDto = UserDto.getUserDtoByUser(user);
                    session.setAttribute("user", userDto);
                    Long unreadCount = notificationService.unreadCount(user.getId(),2);
                    session.setAttribute("unreadCount", unreadCount);
                }
            }

        }
//        if (cookies != null && cookies.length != 0)
//            for (Cookie cookie : cookies) {
//                if (cookie.getName().equals("token") && StringUtils.isNotBlank(cookie.getValue())) {
//                    String token = cookie.getValue();
//                    String type = token.substring(0,2);
//                    String userToken = token.substring(2);
//
//                    if (type.equals("GU")) {
//                        GiteeUserExample giteeUserExample = new GiteeUserExample();
//                        giteeUserExample.createCriteria()
//                                .andTokenEqualTo(userToken);
//                        List<GiteeUser> giteeUsers = giteeUserMapper.selectByExample(giteeUserExample);
//                        if (giteeUsers.size() != 0) {
//                            HttpSession session = request.getSession();
//                            UserDto userDto = UserDto.getUserDtoByGiteeUser(giteeUsers.get(0));
//                            session.setAttribute("user", userDto);
//                            Long unreadCount = notificationService.unreadCount(giteeUsers.get(0).getId());
//                            session.setAttribute("unreadCount", unreadCount);
//                        }
//                    }
//                    if (type.equals("UR")){
//                    }
//                    break;
//                }
//            }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }
}
